package com.itlong.cloud.controller.finance;

import com.itlong.cloud.POJO.DTO.operate.OperateCheckAccountByPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateProjectUpdateDTO;
import com.itlong.cloud.POJO.DTO.operate.PropertyFinanceManageGetPageDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateGetProjectFinancePageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.paymenthub.IPropertyFinanceManageClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      运营-物业财务管理控制器
 * </desc>
 *
 * @createDate 2018/09/20
 */
@RestController
@RequestMapping("/finance/project")
@RefreshScope
public class OperatePropertyFinanceManageController extends BaseController {

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    private IPropertyFinanceManageClient iPropertyFinanceManageClient;
    @Autowired
    private IOperateProjectServiceClient iOperateProjectServiceClient;

    /**
     * <desc>
     *      分页获取项目信息
     * </desc>
     *
     * @param propertyFinanceManageGetPageDTO 运营-物业财务管理项目列表查询DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/09/20
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getPage")
    public Object getProjectFinancePage(PropertyFinanceManageGetPageDTO propertyFinanceManageGetPageDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyFinanceManageGetPageDTO= HttpProtocolUtil.parseRequestParamToDTO(PropertyFinanceManageGetPageDTO.class,request);
            if (propertyFinanceManageGetPageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Page<OperateGetProjectFinancePageVO> page = iPropertyFinanceManageClient.getProjectFinancePage(propertyFinanceManageGetPageDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        } catch (Exception e) {
            throw new DataAccessException("【运营-物业财务管理getProjectFinancePage】分页获取项目财务信息失败",e);
        }
    }

    /**
     * <desc>
     *      财务启用或禁用项目
     * </desc>
     *
     * @param operateProjectUpdateDTO 项目信息更新DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/09/20
     */
    @ResponseBody
    @PostMapping("update")
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PROJECT_UPDATE_LOG_DESC)
    public Object updateProject(OperateProjectUpdateDTO operateProjectUpdateDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateProjectUpdateDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateProjectUpdateDTO.class,request);
            if (StringUtils.isBlank(operateProjectUpdateDTO.getProjectId()) || !operateProjectUpdateDTO.getProjectId().matches("[0-9]{8}")){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_ID_INVALID_ERR.getErrorCode());
            }
            //项目状态
            if (operateProjectUpdateDTO.getStatus() == null || (null != operateProjectUpdateDTO.getStatus() && (operateProjectUpdateDTO.getStatus() != DataStatusEnum.NORMAL.getType()
                    && operateProjectUpdateDTO.getStatus() != DataStatusEnum.BAN.getType()))){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_STATUS_INVALID_ERR.getErrorCode());
            }
            Integer result = iPropertyFinanceManageClient.updateProject(operateProjectUpdateDTO);
            return new MessageVO(operateProjectUpdateDTO.getProjectId(), BaseErrorCodeEnum.SUCCESS.getErrorCode(),result);
        } catch (Exception e) {
            throw new DataAccessException("【运营-物业财务管理】启用或禁用项目失败",e);
        }
    }

    /**
     * <desc>
     *      导出表单信息
     * </desc>
     *
     * @param propertyFinanceManageGetPageDTO 运营-物业财务管理项目列表查询DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/09/20
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("export")
    public Object export(PropertyFinanceManageGetPageDTO propertyFinanceManageGetPageDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyFinanceManageGetPageDTO= HttpProtocolUtil.parseRequestParamToDTO(PropertyFinanceManageGetPageDTO.class,request);
            if (propertyFinanceManageGetPageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            List<OperateGetProjectFinancePageVO> operateGetProjectFinancePageVOList = iPropertyFinanceManageClient.getProjectFinanceList(propertyFinanceManageGetPageDTO);
            if (operateGetProjectFinancePageVOList == null || operateGetProjectFinancePageVOList.isEmpty()) {
                return new MessageVO(OperateErrorCodeEnum.EXPORT_DATA_EMPTY_ERR.getErrorCode());
            }
            String[] title = {"序号","项目编号","项目名称","物业名称","可提现金额","实时账户余额","手机号码","创建时间","状态"};
            short rowHeight= 420;
            //创建excel工作簿
            HSSFWorkbook workbook=new HSSFWorkbook();
            //创建工作表sheet并设置简单格式
            HSSFSheet sheet=workbook.createSheet();
            sheet.setDefaultColumnWidth(15);
            //创建第一行
            HSSFRow row=sheet.createRow(0);
            row.setHeight(rowHeight);
            HSSFCell cell=null;
            //插入第一行数据的表头
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            //写入数据
            for (int projectIndex = 0; projectIndex < operateGetProjectFinancePageVOList.size(); projectIndex++) {
                OperateGetProjectFinancePageVO operateGetProjectFinancePageVO = operateGetProjectFinancePageVOList.get(projectIndex);
                int rowIndex = projectIndex + 1; // 第一行已为标题行
                HSSFRow dataRow = sheet.createRow(rowIndex);
                dataRow.setHeight(rowHeight);
                HSSFCell noteCell = dataRow.createCell(0);
                noteCell.setCellValue(rowIndex);
                noteCell = dataRow.createCell(1);
                noteCell.setCellValue(operateGetProjectFinancePageVO.getProjectId());
                noteCell = dataRow.createCell(2);
                noteCell.setCellValue(operateGetProjectFinancePageVO.getProjectName());
                noteCell = dataRow.createCell(3);
                noteCell.setCellValue(operateGetProjectFinancePageVO.getPropertyName());
                noteCell = dataRow.createCell(4);
                noteCell.setCellValue(StringUtils.isBlank(operateGetProjectFinancePageVO.getAllowedCashWithdrawl()) ? "0.00" : operateGetProjectFinancePageVO.getAllowedCashWithdrawl());
                noteCell = dataRow.createCell(5);
                noteCell.setCellValue(StringUtils.isBlank(operateGetProjectFinancePageVO.getAccountAmount()) ? "0.00" : operateGetProjectFinancePageVO.getAccountAmount());
                noteCell = dataRow.createCell(6);
                noteCell.setCellValue(operateGetProjectFinancePageVO.getPhoneNum());
                noteCell = dataRow.createCell(7);
                noteCell.setCellValue(operateGetProjectFinancePageVO.getCreateTime());
                noteCell = dataRow.createCell(8);
                noteCell.setCellValue(operateGetProjectFinancePageVO.getStatus() == DataStatusEnum.NORMAL.getType() ? "启用" : "禁用");
            }
            String fileName = String.format("%s_FinanceManage_%s.xls",propertyFinanceManageGetPageDTO.getToken(),DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            byte[] content = os.toByteArray();
            InputStream exportFileStream = new ByteArrayInputStream(content);
            String exportFileUrl = uploadFile(exportFileStream,fileName);
            if (StringUtils.isBlank(exportFileUrl)){
                return new MessageVO(OperateErrorCodeEnum.EXPORT_FILE_SAVE_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) exportFileUrl);
        } catch (Exception e) {
            throw new DataAccessException("【运营-物业财务管理】导出Excel失败",e);
        }
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileName 文件名称
     * @return 文件上传成功后会返回Url,否则返回空
     * @author wangzhi
     * @createDate 2018/09/20
     */
    private String uploadFile(InputStream inputStream, String fileName) throws IOException {
        String fileUrl = "";
        String fileType = StringHandlerUtil.copySubStr(fileName, fileName.lastIndexOf('.') + 1, fileName.length());
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.EXPORT_EXCEL_ZHANG_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

}
